<template>
  <div class="search-result">
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      :error.sync="error"
      error-text="加载失败，请点击重试"
      @load="onLoad"
    >
      <van-cell
        v-for="(article, index) in list"
        :key="index"
        :title="article.title"
      />
    </van-list>
  </div>
</template>

<script>
import { getSearchResult } from '@/api/search'

export default {
  name: 'SearchResult',
  components: {},
  props: {
    searchText: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      page: 1,
      perPage: 20,
      error: false,
    }
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    async onLoad() {
      try {
        //  1.请求获取数据
        const { data } = await getSearchResult({
          page: this.page,
          per_page: this.perPage,
          q: this.searchText,
        })

        // if (Math.random() > 0.5) {
        //   JSON.parse('1123asdasdas')
        // }
        // console.log(data)
        //  2.将数据添加到数组列表中
        const { results } = data.data
        this.list.push(...results)
        //  3.将本次加载中得loading 关闭
        this.loading = false
        //  4.判断是否还有数据 如果还有数据，则重新获取下一个数据得页码
        if (results.length) {
          this.page++
        } else {
          this.finished = true
        }
        //    如果没有则将加载状态 finished设置为结束
      } catch (err) {
        this.error = true
        this.loading = false
      }
    },
  },
}
</script>
<style lang='less' scoped>
</style>
